package com.zj.leetcode.easy;

/**
 * @program: algorithm
 * @description: 字符串相加
 * 415 add-strings
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class AddStrings {
    public static void main(String[] args) {
        String num1 = "19", num2 = "123";
        Solution solution = new AddStrings().new Solution();

        System.out.println(solution.addStrings(num1, num2));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public String addStrings(String num1, String num2) {

            int i = num1.length() - 1;
            int j = num2.length() - 1;

            int cacheNum = 0;

            StringBuffer ret = new StringBuffer();
            while (i >= 0 && j >= 0) {
                int num = Character.getNumericValue(num1.charAt(i))
                        + Character.getNumericValue(num2.charAt(j))
                        + cacheNum;
                if (num >= 10) {
                    cacheNum = 1;
                    ret.append(String.valueOf(num % 10));
                } else {
                    cacheNum = 0;
                    ret.append(String.valueOf(num));
                }
                --i;
                --j;
            }

            while (i >= 0) {
                int num = Character.getNumericValue(num1.charAt(i))
                        + cacheNum;
                if (num >= 10) {
                    cacheNum = 1;
                    ret.append(String.valueOf(num % 10));
                } else {
                    cacheNum = 0;
                    ret.append(String.valueOf(num));
                }
                --i;
            }

            while (j >= 0) {
                int num = Character.getNumericValue(num2.charAt(j))
                        + cacheNum;
                if (num >= 10) {
                    cacheNum = 1;
                    ret.append(String.valueOf(num % 10));
                } else {
                    cacheNum = 0;
                    ret.append(String.valueOf(num));
                }
                --j;
            }

            if(cacheNum > 0){
                ret.append(1);
            }
            return this.overturn(ret.toString());

        }

        private String overturn(String str) {
            char[] chars = str.toCharArray();
            int head = 0;
            int tail = str.length() - 1;
            while (head < tail) {

                chars[head] ^= chars[tail];
                chars[tail] ^= chars[head];
                chars[head] ^= chars[tail];

                head++;
                tail--;
            }
            return String.valueOf(chars);
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}